/*
 * Author: 李波（Edwin Lee)
 * Date: 2024-06-16 20:38:26
 * FilePath: /chat/src/server/model/usermodel.cc
 * LastEditTime: 2024-07-11 00:23:54
 * version: 1.0
 * Description: 
 */

#include "usermodel.h"
#include "connection.h"
#include "commonConnectionPool.h"

#include <iostream>

bool UserModel::insert(User& user)
{
    //组装sql语句
    char sql[1024] = {0};
    // undo:密码不会用明文保存，这里后期可以做改动
    sprintf(sql,"insert into user(name,password,state) values('%s','%s','%s')",
        user.getName().c_str(),user.getPwd().c_str(), user.getState().c_str());
    ConnectionPool& cnp = ConnectionPool::getInstance();
    shared_ptr<Connection> conn = cnp.getConnection();
    if(conn != nullptr)
    {
        if(conn->update(sql))
        {
            // 获取插入成功的用户数据生成的主键id
            user.setId(conn->getInsertId());
            return true;
        }
    }
    return false;
}

User UserModel::query(int id)
{
    //组装sql语句
    char sql[1024] = {0};
    sprintf(sql,"select * from user where id=%d",id);
    ConnectionPool& cnp = ConnectionPool::getInstance();
    shared_ptr<Connection> conn = cnp.getConnection();
    if(conn != nullptr)
    {
        MYSQL_RES* res = conn->query(sql);
        if(res != nullptr)
        {
            MYSQL_ROW row = mysql_fetch_row(res);
            if(row != nullptr)
            {
                User user;
                user.setId(atoi(row[0]));
                user.setName(row[1]);
                user.setPwd(row[2]);
                user.setState(row[3]);
                mysql_free_result(res);
                return user;
            }
            mysql_free_result(res);
        }
    }
    return User();
}

bool UserModel::updateState(User user)
{
    //组装sql语句
    char sql[1024] = {0};
    // undo:密码不会用明文保存，这里后期可以做改动
    sprintf(sql,"update user set state='%s' where id=%d",user.getState().c_str(),user.getId());
    //printf("UserModel::updateState-sql:%s\n",sql);
    ConnectionPool& cnp = ConnectionPool::getInstance();
    shared_ptr<Connection> conn = cnp.getConnection();
    if(conn != nullptr)
    {
        if(conn->update(sql))
        {
            printf("update success!");
            return true;
        }
    }
    return false;
}

void UserModel::resetState()
{
    ConnectionPool& cnp = ConnectionPool::getInstance();
    shared_ptr<Connection> conn = cnp.getConnection();
    if(conn != nullptr)
    {
        conn->update("update user set state='offline' where state = 'online'");
    }
}